<?php

namespace Cck\ArticlesSystem\Http\Controllers;

use Illuminate\Http\Request;
use Cck\ArticlesSystem\Http\Models\Role;
use Cck\ArticlesSystem\Http\Resources\RoleResource;
use Cck\ArticlesSystem\Http\Requests\RoleStoreRequest;
use Cck\ArticlesSystem\Http\Requests\RoleUpdateRequest;

class RolesController extends Controller
{
    public function index(Request $request)
    {
        $pageSize = (int)max($request->query('page_size', 15), 10);
        $page = (int)max($request->query('page', 1), 1);

        return RoleResource::collection(
            Role::query()->with($this->getWith())->paginate($pageSize, ['*'], 'page', $page)
        );
    }

    public function all()
    {
        return RoleResource::collection(
            Role::with($this->getWith())->get()
        );
    }

    public function store(RoleStoreRequest $request)
    {
        $data = $request->validated();

        /** @var Role $role */
        $role = Role::query()->create($data);

        $data['permissions'] && $role->permissions()->attach($data['permissions']);

        return new RoleResource($role);
    }

    public function update(Role $role, RoleUpdateRequest $request)
    {

        $data = $request->validated();

        $role->update($data);

        isset($data['permissions']) && $role->permissions()->sync($data['permissions']);

        return ['status' => true];
    }

    public function destroy(Request $request)
    {
        $ids = $request->input('ids', []);

        if (!is_array($ids)) {
            return ['status' => false, 'message' => '请传递要删除的ID数组'];
        }

        $ids = array_filter(array_unique(array_map('intval', $ids)));

        if (!count($ids)) {
            return ['status' => false, 'message' => '请传递要删除的ID数组'];
        }

        \DB::beginTransaction();

        $count = Role::query()->whereIn('id', $ids)->delete();

        if (count($ids) !== $count) {
            \DB::rollBack();

            return ['status' => false, 'message' => '删除失败'];
        }

        \DB::commit();

        return ['status' => true];
    }
}
